import React, { useState } from "react";
import { Tabs, Input } from "antd";
import type { TabsProps } from "antd";
import { InboxOutlined } from "@ant-design/icons";
import type { UploadProps } from "antd";
import { message, Upload } from "antd";
import { useControllableValue } from "ahooks";
const { Dragger } = Upload;

async function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const fileRender = new FileReader();

    fileRender.readAsDataURL(file);

    fileRender.onload = (e) => {
      const base64String = e.target?.result;
      resolve(base64String as string);
    };

    fileRender.onerror = (err) => {
      console.log("加载错误", err);
      reject(err);
    };
  });
}

interface LoadUploadFileProps {
  onChage?: (url: string) => void;
}

const LocalUploadFile: React.FC<LoadUploadFileProps> = ({ onChage }) => {
  const [fileList, setFileList] = useState<UploadProps["fileList"]>([]);
  const props: UploadProps = {
    name: "file",
    multiple: false,
    async beforeUpload(file) {
      console.log("beforeUpload:", file);
      const isMp3 = file.type === "audio/mpeg";
      if (isMp3) {
        const url = await fileToBase64(file);
        if (onChage) {
          onChage(url);
        }
        setFileList([file]);
      } else {
        message.error("请上传mp3文件");
        setFileList([]);
      }
      return false;
    },
    onRemove() {
      setFileList([]);
    },
    fileList,
  };
  return (
    <Dragger {...props}>
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">点击或拖拽文件到此处</p>
    </Dragger>
  );
};

interface AppPropsInt {
  handleOk?: (url: string) => void;
  value?: string;
  onChange?: (val: string) => void;
}

const App: React.FC<AppPropsInt> = (props) => {
  const [url, setUrl] = useControllableValue(props, {
    defaultValue: "",
    valuePropName: "value",
  });
  const onUrlChange = (url: string) => {
    console.log("url:", url);
    setUrl(url);
  };

  const items: TabsProps["items"] = [
    {
      key: "url",
      label: "在线链接",
      children: (
        <Input
          onChange={(e) => onUrlChange(e.target.value)}
          placeholder="请输入音频的在线链接"
        />
      ),
    },
    {
      key: "local-file",
      label: "本地文件",
      children: <LocalUploadFile onChage={onUrlChange} />,
    },
  ];

  const onTabsChange = (key: string) => {
    console.log(key);
    setUrl("");
  };

  return (
    <>
      <Tabs defaultActiveKey="1" items={items} onChange={onTabsChange} />
      {url ? (
        <div className="w-full py-4">
          <audio src={url} controls></audio>
        </div>
      ) : null}
    </>
  );
};

export default App;
